package mongodb.general.operator.nodb.utils;

import com.alibaba.fastjson.JSONObject;
import mongodb.general.operator.nodb.vo.SpecialFieldNameEnum;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 请求数据处理逻辑类
 */
public class ReqHandleUtils {
    /**
     * 前置参数操作
     */
    public static String preReqOperator(JSONObject infoDto,boolean add) throws Exception {
        String tableName = "";
        //前端表名表示改变，兼容表名
//        if (StrUtil.isNotBlank(infoDto.getString("serviceName"))) {
//            infoDto.put("tableName", infoDto.getString("serviceName"));
//            infoDto.remove("serviceName");
//        }
        Map<String, Object> entity = (Map) infoDto;
        //时间转换
        DateUtils.transformStringToDate(entity);
        ReqHandleUtils reqHandleUtils = new ReqHandleUtils();
        //新增追加信息
        reqHandleUtils.addTimeAndDelFlagInfo(infoDto,add);
        //获取表名，去除特殊字段
        tableName = reqHandleUtils.getTableNameAndRemoveFlagKey(infoDto);
        return tableName;
    }

    /**
     * 为对象添加时间信息和删除标志
     * @param infoDto
     */
    private void addTimeAndDelFlagInfo(Object infoDto,boolean add){
        Map<String, Object> entity = (Map<String, Object>) infoDto;
        LocalDateTime currentLocalDateTime = LocalDateTime.now();
        if(add){
            entity.computeIfAbsent("createTime", key -> currentLocalDateTime);
            entity.put("delFlag",0);
        }
        entity.put("updateTime", currentLocalDateTime);
    }
    /**
      * tableName 为空直接报错
      * 获取表名，去除特殊字段
      */
    private String getTableNameAndRemoveFlagKey(Object infoDto) throws Exception {
        Map entity = (Map) infoDto;
        if (!entity.containsKey("tableName")) {
            throw new Exception("参数tableName不能为空");
        }
        String tableName = "";
        for(Object key : entity.keySet()){
            String keyValue = key.toString();
            if("tableName".equals(keyValue)){
                tableName = entity.get(keyValue).toString();
            }
        }
        //移除特殊字段
        removeFlagKey(infoDto);
        return tableName;
    }
    /**
     * todo 最好有标识符结尾
     * 移除特殊字段
     * @param infoDto
     */
    private void removeFlagKey(Object infoDto){
        Map entity = (Map)infoDto;
        for(SpecialFieldNameEnum specialName : SpecialFieldNameEnum.values()){
            entity.remove(specialName.toString());
        }
    }
}

